import { AfterViewInit, Component, NgZone, OnInit } from '@angular/core';
import { timer } from 'rxjs';

@Component({
  selector: 'app-zone-child',
  templateUrl: './zone-child.component.html',
  styleUrls: ['./zone-child.component.scss']
})
export class ZoneChildComponent implements OnInit, AfterViewInit {

  constructor(private _ngZone: NgZone) { }

  ngOnInit(): void {
    // this._testInvoke();
  }

  public ngAfterViewInit() {
    Promise.resolve().then(() => {
      console.log('child promise1');
    });

    Promise.resolve().then(() => {
      console.log('child promise2');
    });

    setTimeout(() => {
      console.log('child Timer1')
    });

    setTimeout(() => {
      console.log('child Timer2')
    });
  }

  private _testInvoke(): void {
    this._ngZone.runOutsideAngular(() => {
      const logZone = Zone.current.fork({
        name: 'logZone',
        onInvoke: (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) => {
          console.log('onInvoke enter');
          console.log(delegate);
          parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
          console.log('onInvoke leave');
        },
        onHasTask: (parentZoneDelegate, currentZone, targetZone, hasTaskState) => {
          console.log('onHasTask enter');
          console.log(hasTaskState);
          parentZoneDelegate.hasTask(targetZone, hasTaskState);
          console.log('onHasTask leave');
        },
        onInvokeTask: (parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) => {
          console.log('onInvokeTask enter');
          console.log(task);
          parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
          console.log('onInvokeTask leave');
        }
      });

      // 在 logZone 的环境下调用 mayApp 函数
      logZone.run(function myApp() {
        /*console.log(Zone.current.name, 'queue promise');
        Promise.resolve('OK').then((value) => {
          console.log(Zone.current.name, 'Promise', value);
        });*/

        console.log(Zone.current.name, 'queue setTimeout');
        setTimeout(() => {
          console.log('setTimeOut');
        })

        // console.log(Zone.current.name, 'Observable');
        // timer(100).subscribe((val) => {
        //   console.log('rx', val);
        // })
      });
    })
  }

  private _testTryFinally() {
    const fn = function () {
      new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(1);
        }, 3000)
      }).then((val) => {
        console.log('promise', val)
      })
    }

    try {
      fn();
    } finally {
      console.log('finally')
    }
  }

}
